package com.biz.primus.ms.member.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.util.RedisUtil;
import com.biz.primus.ms.member.dao.ro.MemberAddressLabelRo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import redis.clients.jedis.Tuple;

import java.util.*;

/**
 *
 * @author jun.liu
 * @date 2017年10月23日
 * @reviewer
 * @see
 */
@Repository
public class MemberAddressLabelRedisDao extends CrudRedisDao<MemberAddressLabelRo, Long>
{

    private String memberIdAndLabelNameMappingKey(Long memberId, String labelName)
    {
        return getKeyByParams("memberId", memberId, "labelName", labelName);
    }

    /**
     * 保存
     */
    @Override
    public void save(MemberAddressLabelRo ro)
    {
        super.save(ro);
        if (ro.getMemberId() != null && ro.getMemberId() != 0L)
        {
            if (StringUtils.isNotBlank(ro.getLabelName()))
            {
                set(this.memberIdAndLabelNameMappingKey(ro.getMemberId(), ro.getLabelName()), RedisUtil.toByteArray(ro.getId()));
            }
        }

    }

    public List<MemberAddressLabelRo> findByMemberId(Long memberId){
        Set<Tuple> tuples = super.zrevrangeWithScore(super.getFieldSortedSetKey("memberId", memberId), 0, -1);
        if(CollectionUtils.isEmpty(tuples)) {
            return Collections.emptyList();
        }
        Iterator<Tuple> iterator = tuples.iterator();
        List<Long> ids = Lists.newArrayList();
        while (iterator.hasNext()) {
            ids.add(Long.parseLong(iterator.next().getElement()));
        }
        return findByIds(ids);
    }

    public boolean findByMemberAndLabelNameIsExist(Long memberId, String labelName) {
        if (memberId != null && memberId != 0L && StringUtils.isNotBlank(labelName))
        {
            byte[] bs = super.get(this.memberIdAndLabelNameMappingKey(memberId, labelName));
            if (bs == null)
            {
                return false;
            }
            Long id = RedisUtil.byteArrayToLong(bs);
            if(findOne(id) == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        else
        {
            return false;
        }
    }

    public MemberAddressLabelRo findByMemberAndLabelName(Long memberId, String labelName) {
        if (memberId != null && memberId != 0L && StringUtils.isNotBlank(labelName))
        {
            byte[] bs = super.get(this.memberIdAndLabelNameMappingKey(memberId, labelName));
            if (bs == null)
            {
                return null;
            }
            return findOne(RedisUtil.byteArrayToLong(bs));
        }
        else
        {
            return null;
        }
    }
}